package proj.reseau;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ClientResponse implements Runnable{

	Socket socket;
	Fichiers fichiers;
	BufferedReader in = null;
	OutputStreamWriter out = null;

	public ClientResponse(Config config, Socket sock, Fichiers fichiers)
	{
		this.fichiers=fichiers;
		this.socket=sock;
		try {
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new OutputStreamWriter(socket.getOutputStream());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if (in == null || out == null) {
			System.err.println("erreur de lecture/ecriture dans une ClientResponse socket");
		}
		
		if (socket == null) {
			System.err.println("erreur de connexion");
		}
	}

	public BufferMap interested(Fichier f, Socket sock)
	{
		String response=null;
		String msg = "interested " + f.getFileName();
		BufferMap bf=null;
		try {

			out.write(msg);
			out.flush();
			response = in.readLine();
			System.err.println("requète envoyée: " + msg);
			System.err.println(response);
			
			String key=response.substring(response.indexOf(" ", 0), response.indexOf(" ", 10));
			String bufferMap=response.substring(response.indexOf(" ", 10), response.indexOf(" ", 10)+(int)((f.getTaille()/f.getPiece_size())/8));
			bf=new BufferMap((int)(f.getTaille()/f.getPiece_size()));
			bf.setBufferMap(bufferMap);

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bf;
	}
	
	private void anwser(String s)
	{
		//System.out.println("debut de anwser "+s);
		if(s.matches("^interested.*"))
		{
			String key=s.substring(11, 43);
			System.err.println("(interested)la key reçue est :"+key+"\n");
			Fichier file=fichiers.getFichier(key);
			String rep="have "+key+" "+file.getBufferMap().toBinaryString();
			System.err.println("requète envoyée : " + rep);
			try {
				out.write(rep);
				out.flush();
			}catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		else if(s.matches("^getpieces.*"))
		{
			String key = s.substring(10, 42);
			System.err.println("(getpieces)la key reçue est :"+key+"\n");
			Fichier file = fichiers.getFichier(key);
			List<Integer> list_pieces = new ArrayList<Integer>();
			System.err.println(s);
			String pieces = s.substring(44, s.lastIndexOf(']'));
			String[] tokens = pieces.split(" ");
			for(String t : tokens)
			{
				list_pieces.add(Integer.parseInt(t));
			}
			
			String response = "data " + key + " [" + piecesToString(list_pieces, file) + "]";
			try {
				System.out.println("message data envoyé : "+response);
				System.out.println("taille de la reponse envoyée" + response.length());
				out.write(response);
				out.flush();
			}catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public String piecesToString(List<Integer> listPieces, Fichier file)
	{
		String res = new String();
		int pieceSize = file.getPiece_size();
		for(Integer i = 0; i < listPieces.size(); i++)
		{
			res = res.concat(i.toString() + ":");
			try {
				InputStream inputStream = new FileInputStream(file.getPath());
				inputStream.skip(i*pieceSize);
				byte[] tmp = new byte[pieceSize];
				int sizelast = pieceSize;
				boolean last = false;
				if(i == (int) Math.floor(((double)file.getTaille())/(double)file.getPiece_size()))
				{
					System.out.println(i+" DERNIERE PIECE");
					last = true;
					sizelast = inputStream.read(tmp);
					System.out.println("taille de la derniere piece : "+sizelast);
				}
				byte[] b = new byte[sizelast];
				if(!last)
					inputStream.read(b, 0, pieceSize);
				else
				{
					for(int j = 0; j < sizelast; j++)
						b[j] = tmp[j];
					System.out.println("recuperation de la derniere piece");
				}
				char[] piece2 = new char[b.length];
				for(int j = 0; j < b.length; j++)
				{
					piece2[j] = (char)b[j];
				}
				String piece = new String(piece2);
				System.out.println("String size : "+piece.length());
				System.out.println("char[] size : "+piece2.length);
				res = res.concat(piece);
				if(i != listPieces.size()-1)
					res = res.concat(" ");
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		return res;
	}

	@Override
	public void run() {


		
		// TODO Auto-generated method stub
		try {
			//System.out.println("On est dans la place yo");
			
				//userInput = in.readLine();
				anwser(in.readLine());

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}





}
